package com.jqing.lib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jqing.lib.R;
import com.jqing.lib.tools.TextTools;

/**
 * Created by chshqiang on 15-6-15.
 * 升级版EditText
 * 支持输入栏内左边标题显示  右边有清除按钮和密码显示按钮
 */
public class UpgradedEditText extends RelativeLayout implements View.OnClickListener, View.OnTouchListener {
    private EditText editText;
    private TextView textView;
    private Button upgradedTextClear;
    private Button upgradedPasswordVisible;

    private int inputType;

    public UpgradedEditText(Context context) {
        super(context);
        initializeView(context, null);
    }

    public UpgradedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeView(context, attrs);
    }

    public UpgradedEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initializeView(context, attrs);
    }

    private void initializeView(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.upgraded_edit_text, this);

        editText = (EditText) findViewById(R.id.upgradedEditText);
        textView = (TextView) findViewById(R.id.upgradedEditTitle);
        upgradedTextClear = (Button) findViewById(R.id.upgradedEditClear);
        upgradedPasswordVisible = (Button) findViewById(R.id.upgradedPasswordVisible);

        upgradedTextClear.setOnClickListener(this);
        upgradedPasswordVisible.setOnTouchListener(this);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isPasswordInputType(inputType)) {
                    upgradedPasswordVisible.setVisibility(0 == s.length() ? INVISIBLE : VISIBLE);
                } else {
                    upgradedTextClear.setVisibility(0 == s.length() ? INVISIBLE : VISIBLE);
                }
            }
        });

        Typeface font = Typeface.createFromAsset(context.getAssets(), "font/fontawesome_webfont.ttf");
        upgradedTextClear.setTypeface(font);
        upgradedPasswordVisible.setTypeface(font);

        upgradedTextClear.setVisibility(INVISIBLE);
        upgradedPasswordVisible.setVisibility(INVISIBLE);

        setAttributeSet(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int left = textView.getWidth();
        int right = upgradedTextClear.getWidth();
        int top = editText.getPaddingTop();
        int bottom = editText.getPaddingBottom();

        editText.setPadding(left, top, right, bottom);

        int labelPaddingLeft = textView.getPaddingLeft();
        int labelPaddingRight = textView.getPaddingRight();

        textView.setPadding(labelPaddingLeft, top, labelPaddingRight, bottom);
    }

    @Override
    public void onClick(View v) {
        editText.setText("");
        editText.setFocusable(true);
        editText.requestFocus();
    }

    private void setAttributeSet(Context context, AttributeSet attributeSet) {
        if (null == attributeSet) {
            return;
        }

        TypedArray arr = context.obtainStyledAttributes(attributeSet, R.styleable.UpgradedEditText);

        if (arr.hasValue(R.styleable.UpgradedEditText_android_gravity)) {
            editText.setGravity(arr.getInt(R.styleable.UpgradedEditText_android_gravity, Gravity.LEFT));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_minEms)) {
            editText.setMinEms(arr.getInt(R.styleable.UpgradedEditText_android_minEms, -1));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_maxEms)) {
            editText.setMaxEms(arr.getInt(R.styleable.UpgradedEditText_android_maxEms, Integer.MAX_VALUE));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_singleLine)) {
            editText.setSingleLine(arr.getBoolean(R.styleable.UpgradedEditText_android_singleLine, true));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_background)) {
            editText.setBackgroundResource(arr.getResourceId(R.styleable.UpgradedEditText_android_background, 0));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_textSize)) {
            float textSize = arr.getDimension(R.styleable.UpgradedEditText_textSize, R.dimen.abc_action_bar_subtitle_text_size);

            editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            upgradedTextClear.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            upgradedPasswordVisible.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }

        if (arr.hasValue(R.styleable.UpgradedEditText_hint)) {
            editText.setHint(arr.getString(R.styleable.UpgradedEditText_hint));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_imeOptions)) {
            editText.setImeOptions(arr.getInt(R.styleable.UpgradedEditText_android_imeOptions, EditorInfo.IME_ACTION_DONE));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_text)) {
            setEditText(arr.getString(R.styleable.UpgradedEditText_text));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_label)) {
            setLabel(arr.getString(R.styleable.UpgradedEditText_label));
        }
        if (arr.hasValue(R.styleable.UpgradedEditText_android_inputType)) {
            setEditInput(arr.getInt(R.styleable.UpgradedEditText_android_inputType, InputType.TYPE_CLASS_TEXT));
        }

        arr.recycle();
    }

    private void setEditInput(int inputType) {
        this.inputType = inputType;
        editText.setInputType(inputType);
    }

    private static boolean isPasswordInputType(int inputType) {
        final int variation =
                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
        return variation
                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
                || variation
                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
                || variation
                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
    }

    public void setEditText(String text) {
        if (null == text) {
            editText.setText("");
        } else {
            editText.setText(text);
            editText.setSelection(text.length());
        }
    }

    public void setLabel(String label) {
        if (null == label) {
            textView.setText("");
        } else {
            textView.setText(label);
        }
    }

    @Override
    public void setFocusable(boolean focusable) {
//        super.setFocusable(focusable);

        editText.setFocusable(focusable);
        editText.requestFocus();
    }

    public void setOnEditorActionListener(TextView.OnEditorActionListener listener) {
        editText.setOnEditorActionListener(listener);
    }

    public String getText() {
        if (null == editText || TextTools.isEmpty(editText.getText().toString()))
            return "";

        return editText.getText().toString();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                editText.setInputType(EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD);
                editText.setSelection(editText.length());
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                editText.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD);
                editText.setSelection(editText.length());
                break;
        }
        return false;
    }
}
